package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.figin.UserFeignApi;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class CookieRefreshFilter extends ZuulFilter {
    @Autowired
    private UserFeignApi userFeignApi;
    @Override
    public String filterType() {

        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
       String token= CookieUtil.getCookieVal(request,"userToken");
       if (!StringUtils.isEmpty(token)){
           return true;//执行下面的run方法
       }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        //延迟redis的过期时间（会员服务操作）zull远程调用会员服务
        String token= CookieUtil.getCookieVal(request,"userToken");
        Result<Boolean> result = userFeignApi.refreshToken(token);
        if (result!=null&&result.getCode()==200&&result.getData()){
            //延迟cookie的过期时间
            CookieUtil.addCookie("userToken",token,1800,response);
        }
        //这个filter没过，后面的filter也不用走了
        context.setSendZuulResponse(false);



        return null;
    }
}
